import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/common/su_icon.dart';
import 'package:love_app/enum/onload_type.dart';
import 'package:love_app/enum/sex.dart';
import 'package:love_app/model/community_model.dart' as CTYModel;
import 'package:love_app/pages/community/common_ui/show_community_input.dart';
import 'package:love_app/pages/community/common_ui/warp_image_ui.dart';
import 'package:love_app/pages/community/null_item.dart';
import 'package:love_app/providers/attention_provider.dart';
import 'package:love_app/providers/latest_provider.dart';
import 'package:love_app/providers/recommend_provider.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/providers/user_center_provider.dart';
import 'package:love_app/routes/application.dart';
import 'package:love_app/routes/routes.dart';
import 'package:love_app/service/comment_details_api.dart';
import 'package:love_app/service/community_api.dart';
import 'package:love_app/service/dynamic_agree_api.dart';
import 'package:love_app/style/space_header.dart.dart';
import 'package:provider/provider.dart';

// 社区三个页面内容共同的样式（只关心数据）
class ContentUI extends StatefulWidget {
  final String providerType; // 必须是社区页面共享数据
  // final CTYModel.Data data; // 社区页面数据

  const ContentUI({Key key, @required this.providerType}) : super(key: key);

  @override
  _ContentUIState createState() => _ContentUIState();
}

class _ContentUIState extends State<ContentUI> {
  dynamic _provider; // 必须是社区页面共享数据
  // CTYModel.Data _itemData; // 社区页面数据
  ScrollController _scrollController; // 滚动条监听控制器
  ShareProvider _shareProvider;
  EasyRefreshController _easyRefreshController; // 加载控制器
  OnLoadType _onLoadType;

  @override
  void initState() {
    super.initState();
    // 为了方便使用
    // _itemData = widget.data;
    _easyRefreshController = EasyRefreshController();
    _onLoadType = OnLoadType.loading;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    if (widget.providerType == 'recommend') {
      _provider = Provider.of<RecommendProvider>(context, listen: false);
    } else if (widget.providerType == 'latest') {
      _provider = Provider.of<LatestProvider>(context, listen: false);
    } else if (widget.providerType == 'attention') {
      _provider = Provider.of<AttentionProvider>(context, listen: false);
    } else if (widget.providerType == 'userCenter') {
      _provider = Provider.of<UserCenterProvider>(context, listen: false);
    }
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _addlistenOffset();
    return _centent();
  }

  // 滚动条监听初始化
  void _addlistenOffset() {
    _scrollController = ScrollController(initialScrollOffset: _provider.offset);
    _scrollController.addListener(() {
      _provider.offset = _scrollController.offset;
    });
  }

  // 页面内容
  Widget _centent() {
    List<CTYModel.Data> allItemData = _provider.getAllItem();
    return EasyRefresh.custom(
      header: SpaceHeader(),
      controller: _easyRefreshController,
      firstRefresh: _provider.isFirst,
      scrollController: _scrollController,
      bottomBouncing: true,
      enableControlFinishLoad: true,
      // emptyWidget: _sliverLenghtIsZero(),
      onRefresh: () async {
        // 触发下拉加载
        _onLoadType = OnLoadType.loading;
        _provider.clean();
        setState(() {});
        await _onLoad();
      },
      onLoad: () async {
        // 触发上拉加载
        await _onLoad();
        _provider.isFirst = false;
      },
      slivers: <Widget>[
        _sliver(allItemData),
      ],
    );
  }

  // 上拉加载
  Future<void> _onLoad() async {
    try {
      if (_provider.isEndPage == false) {
        int page = _provider.page;
        String path = _provider.apiPath + page.toString();
        CTYModel.CommunityModel communityModel =
            await CommunityApi().getCommunityData(_shareProvider.token, path);
        if (communityModel.data.isEmpty == true) {
          _provider.isEndPage = true;
          setState(() {
            _onLoadType = OnLoadType.hasLoad;
          });
          _easyRefreshController.finishLoad(success: true, noMore: true);
        } else {
          _provider.page++;
          communityModel.data.forEach((item) {
            _provider.setAllItem(item.id, item);
          });
          setState(() {});
          _easyRefreshController.finishLoad(success: true, noMore: false);
        }
      } else {
        _easyRefreshController.finishLoad(success: true, noMore: true);
      }
    } catch (error) {
      _easyRefreshController.finishLoad(success: true, noMore: false);
      SuDialog.showToast("加载异常");
      Su.suPrints(error);
    }
  }

  // 页面的slivers
  Widget _sliver(List<CTYModel.Data> allItemData) {
    if (allItemData.length == 0) {
      Widget nullWidget = _onLoadType == OnLoadType.hasLoad
        ? _sliverLenghtIsZero()
        : Scrollbar(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  NullItem(),
                  NullItem(),
                ],
              ),
            ),
          );
      return SliverList(
        delegate: SliverChildListDelegate(
          [
            nullWidget
          ],
        ),
      );
    }

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          int id = allItemData[index].id; // 数据库对应的id
          Widget widgetItem = BuildArticleItem(
            textShowAll: false,
            showImages: _provider.showImages(id),
            token: _shareProvider.token,
            isAttention: false,
            uid: _shareProvider.uid,
            isNextPage: true,
            provider: _provider,
            providerType: widget.providerType,
            itemData: allItemData[index],
          );
          return InkWell(
            onTap: () {
              // Application.router.navigateTo(context, "/detailsItem?itemID=$id");
            },
            child: widgetItem,
          );
        },
        childCount: allItemData.length,
      ),
    );
  }

  // 当长度为零的时候页面
  Widget _sliverLenghtIsZero() {
    return Center(
      child: Container(
        padding: EdgeInsets.only(
          top: Su().h(100),
        ),
        child: Column(
          children: <Widget>[
            Image.asset(
              "images/other/attention_null.png",
            ),
            Text(
              "暂无内容",
              style: Su().textStyle(Color.fromRGBO(128, 128, 128, 1), 24),
            ),
          ],
        ),
      ),
    );
  }
}

// 构建每一个item
class BuildArticleItem extends StatefulWidget {
  final bool textShowAll; // 是否显示全部字体
  final List<String> showImages;
  final String token; // 请求token
  final bool isAttention; // 右边是否是关注按钮
  final int uid; // 当前用户id
  final bool isNextPage; // 点击评论按钮是否是进行路由跳转还是评论
  final dynamic provider; // 推荐页面共享数据
  final String providerType; // provider类型
  final CTYModel.Data itemData;

  const BuildArticleItem(
      {Key key,
      this.textShowAll,
      this.showImages,
      this.token,
      this.isAttention,
      this.uid,
      this.isNextPage,
      this.provider,
      this.itemData,
      this.providerType})
      : super(key: key);

  @override
  _BuildArticleItemState createState() => _BuildArticleItemState();
}

class _BuildArticleItemState extends State<BuildArticleItem> {
  bool _textShowAll; // 是否显示全部字体
  List<String> _showImages;
  String _token; // 请求token
  bool _isAttention; // 右边是否是关注按钮
  int _uid; // 当前用户id
  bool _isNextPage; // 点击评论按钮是否是进行路由跳转还是评论
  dynamic _provider; // 推荐页面共享数据
  String _providerType; // 类型
  CTYModel.Data _itemData; // 每一个社区文章的数据

  @override
  void initState() {
    super.initState();
    _textShowAll = widget.textShowAll;
    _showImages = widget.showImages;
    _token = widget.token;
    _isAttention = widget.isAttention;
    _uid = widget.uid;
    _isNextPage = widget.isNextPage;
    _provider = widget.provider;
    _providerType = widget.providerType;
    _itemData = widget.itemData;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: Su().w(750),
      color: Colors.white,
      margin: EdgeInsets.only(
        bottom: Su().h(14),
      ),
      child: Column(
        children: <Widget>[
          _itemHeader(_itemData),
          _itemCentent(_itemData),
          _itemBottom(_itemData),
        ],
      ),
    );
  }

  // item的头部，包括头像和昵称，日期
  Widget _itemHeader(CTYModel.Data itemData) {
    Widget itemHeaderRight = _isAttention == false
        ? _itemHeaderRightIcon(itemData.id)
        : _itemHeaderRightButton(itemData);

    return Container(
      height: Su().h(114),
      child: Row(
        children: <Widget>[
          _itemHeaderImage(itemData.userInfo.headImg, itemData.userInfo.userId),
          _itemHeaderOther(itemData),
          // _itemHeaderRightIcon(itemData.id),
          itemHeaderRight,
        ],
      ),
    );
  }

  // 用户头像
  Widget _itemHeaderImage(String imagePath, int userId) {
    return InkWell(
      onTap: () {
        if (_provider.isUserPage == false) {
          Application.router
              .navigateTo(context, Routes.userCenter + "?userId=$userId");
        }
      },
      child: Container(
        padding: EdgeInsets.only(
          left: Su().w(20),
          top: Su().h(31),
        ),
        child: ClipOval(
          child: new Image.network(
            imagePath,
            width: Su().w(81),
            height: Su().w(81),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  // 昵称和日期
  Widget _itemHeaderOther(CTYModel.Data itemData) {
    return Expanded(
      child: Container(
        padding: EdgeInsets.only(
          left: Su().w(18),
        ),
        alignment: Alignment.centerLeft,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _itemHeaderName(itemData.userInfo.nickName, itemData.userInfo.sex),
            _itemHeaderDate(itemData.dynamicTime.toString()),
          ],
        ),
      ),
    );
  }

  // 昵称
  Widget _itemHeaderName(String name, int intSex) {
    Sex sex = IntToSex.getSex(intSex);
    Color sexColor = Color.fromRGBO(125, 207, 249, 1); // 默认是男生的色调
    String sexData = "男";
    if (sex == Sex.girl) {
      sexColor = Color.fromRGBO(238, 135, 176, 1);
      sexData = "女";
    }

    return Text(
      name + " · " + sexData,
      style: Su().textStyle(sexColor, 26),
    );
  }

  // 日期
  Widget _itemHeaderDate(String timeStamp) {
    return Text(
      Su().getDate(timeStamp),
      style: Su().textStyle(Color.fromRGBO(179, 179, 179, 1), 20),
    );
  }

  // 三个小圆点
  Widget _itemHeaderRightIcon(int itemId) {
    return PopupMenuButton(
      tooltip: "恭喜发财!!!",
      offset: Offset(0, Su().h(70)),
      icon: Icon(
        Icons.more_horiz,
        color: Color.fromRGBO(204, 204, 204, 1),
      ),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(Su().w(20)),
      ),
      itemBuilder: (BuildContext context) {
        return <PopupMenuItem<String>>[
          PopupMenuItem<String>(
            child: _popupMenuButtonChild("收藏"),
            value: "shoucang",
          ),
        ];
      },
      onSelected: (String action) {
        // switch (action) {
        //   case "shoucang":
        //     print("收藏");
        //     break;
        // } 只有一个不需要判断
      },
      onCanceled: () {
        print("onCanceled");
      },
    );
  }

  // 关注按钮
  Widget _itemHeaderRightButton(CTYModel.Data itemData) {
    Sex sex = IntToSex.getSex(itemData.userInfo.sex);
    Color sexColor = Color.fromRGBO(125, 207, 249, 1); // 默认是男生的色调
    String following = "关注";
    if (itemData.isFollowing == 1) {
      following = "取消关注";
    }
    if (sex == Sex.girl) {
      sexColor = Color.fromRGBO(238, 135, 176, 1);
    }
    Widget attentionButton = InkWell(
      onTap: () async {
        bool success = await CommentDetailsApi()
            .followersUser(_token, itemData.userInfo.userId);
        if (success == true && itemData.isFollowing == 1) {
          SuDialog.showToast("取消关注成功",
              bgColor: sexColor, textColor: Colors.white);
          _provider.updateFollowingById(itemData.id, 0);
        } else if (success == true && itemData.isFollowing == 0) {
          SuDialog.showToast("关注成功",
              bgColor: sexColor, textColor: Colors.white);
          _provider.updateFollowingById(itemData.id, 1);
        }
        setState(() {});
      },
      child: _itemHeaderRightButtonChild(following, sexColor),
    );
    Widget deleteButton = InkWell(
      onTap: () async {
        bool success =
            await CommentDetailsApi().deleteDynamic(_token, itemData.id);
        if (success == true) {
          _provider.deleteItemById(itemData.id);
          Navigator.of(context).pop();
        }
      },
      child: _itemHeaderRightButtonChild("删除", sexColor),
    );

    Widget button =
        _uid == itemData.userInfo.userId ? deleteButton : attentionButton;
    return button;
  }

  // 按钮是关注还说删除
  Widget _itemHeaderRightButtonChild(String text, Color sexColor) {
    return Container(
      alignment: Alignment.center,
      width: Su().w(140),
      height: Su().h(36),
      margin: EdgeInsets.only(
        right: Su().w(36),
        top: Su().h(59),
      ),
      decoration: BoxDecoration(
        color: sexColor,
        borderRadius: BorderRadius.circular(Su().w(18)),
      ),
      child: Text(
        text,
        style: Su().textStyle(Colors.white, 24),
      ),
    );
  }

  // 点击是三个小圆圈事件
  Widget _popupMenuButtonChild(String title) {
    return Container(
      width: Su().w(180),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          Icon(
            SuIcon.stars,
            color: Color.fromRGBO(221, 221, 221, 1),
          ),
          Text(
            title,
            style: Su().textStyle(Color.fromRGBO(34, 34, 34, 1), 28),
          ),
        ],
      ),
    );
  }

  // 文字和图片内容
  Widget _itemCentent(CTYModel.Data itemData) {
    return InkWell(
      onTap: () {
        if (_isNextPage == true) {
          Application.router.navigateTo(context,
              "/detailsPage?itemId=${itemData.id}&providerType=$_providerType");
        }
      },
      child: Container(
        width: Su().w(587),
        padding: EdgeInsets.only(
          left: Su().w(36),
          top: Su().h(21),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _itemCententText(itemData.content),
            _itemCententPics(itemData.pictures, itemData.id),
          ],
        ),
      ),
    );
  }

  // 文字
  Widget _itemCententText(String text) {
    Widget textWidget = _textShowAll == false
        ? Container(
            child: Text(
              text,
              style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 28),
              maxLines: 4,
              overflow: TextOverflow.ellipsis,
            ),
          )
        : Container(
            child: Text(
              text,
              style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 28),
            ),
          );

    return textWidget;
  }

  // 图片
  Widget _itemCententPics(List<CTYModel.Pictures> imagesList, int itemId) {
    return Container(
      padding: EdgeInsets.only(
        top: Su().h(23),
      ),
      child: CommunityWarpImageUI(
        imagesList: imagesList,
        itemId: itemId,
        prividerType: _providerType,
      ),
    );
  }

  // 每个item的底部内容，点赞和评论
  Widget _itemBottom(CTYModel.Data itemData) {
    return Container(
      padding: EdgeInsets.only(
        top: Su().h(30),
        bottom: Su().h(24),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: _itemBottomAgree(itemData),
          ),
          Expanded(
            flex: 1,
            child: _itemBottomCollections(itemData.id),
          ),
        ],
      ),
    );
  }

  // 底部左边（点赞）
  Widget _itemBottomAgree(CTYModel.Data itemData) {
    return Container(
      padding: EdgeInsets.only(
        left: Su().w(117),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          // 爱心图标
          _itemBottomAgreeIcon(itemData),
          Consumer<LatestProvider>(
            builder: (context, LatestProvider latestProvider, _) => Text(
              " " + itemData.agree.toString() + "人羡慕",
              style: Su().textStyle(Color.fromRGBO(128, 128, 128, 1), 22),
            ),
          ),
        ],
      ),
    );
  }

  // 点赞的icon
  Widget _itemBottomAgreeIcon(CTYModel.Data itemData) {
    return InkWell(
      onTap: () async {
        // 点赞的实现方法
        bool success = await DynamicAgreeApi().setAgree(_token, itemData.id);
        if (success) {
          _provider.updateAgreeData(itemData.id);
        }
      },
      child: _consumerAgreeIcon(_providerType),
    );
  }

  // 点赞的按钮
  Widget _consumerAgreeIcon(String providerType) {
    Color noCheck = Color.fromRGBO(221, 221, 221, 1);
    Color check = Color.fromRGBO(240, 52, 28, 1);
    if (providerType == 'recommend') {
      return Consumer<RecommendProvider>(
        builder: (context, RecommendProvider recommendProvider, _) => Icon(
          Icons.favorite,
          color: _itemData.isAgree == 0 ? noCheck : check,
        ),
      );
    } else if (providerType == 'latest') {
      return Consumer<LatestProvider>(
        builder: (context, LatestProvider latestProvider, _) => Icon(
          Icons.favorite,
          color: _itemData.isAgree == 0 ? noCheck : check,
        ),
      );
    } else if (providerType == 'userCenter') {
      return Consumer<UserCenterProvider>(
        builder: (context, UserCenterProvider userCenterProvider, _) => Icon(
          Icons.favorite,
          color: _itemData.isAgree == 0 ? noCheck : check,
        ),
      );
    }
    return Consumer<AttentionProvider>(
      builder: (context, AttentionProvider attentionProvider, _) => Icon(
        Icons.favorite,
        color: _itemData.isAgree == 0 ? noCheck : check,
      ),
    );
  }

  // 底部左边（评论）
  Widget _itemBottomCollections(int itemId) {
    return Container(
      padding: EdgeInsets.only(
        right: Su().w(90),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          // 评论图标
          _collectionIcon(itemId),
          _consumerType(_providerType, itemId),
        ],
      ),
    );
  }

  // 评论按钮， 点击是跳转还是弹出评论框
  Widget _collectionIcon(int itemId) {
    Color mainColor = Color.fromRGBO(221, 221, 221, 1);
    return InkWell(
      onTap: () async {
        if (_isNextPage == true) {
          Application.router.navigateTo(context,
              "/detailsPage?itemId=$itemId&providerType=$_providerType");
        } else {
          await _show(context, itemId);
        }
      },
      child: Icon(
        SuIcon.collections,
        color: mainColor,
      ),
    );
  }

  Widget _consumerType(String providerType, int itemId) {
    String collections = _provider.getItemById(itemId).collections.toString();
    final Widget textWidget = Text(
      "  " + collections,
      style: Su().textStyle(Color.fromRGBO(128, 128, 128, 1), 22),
    );
    if (providerType == 'recommend') {
      return Consumer<RecommendProvider>(
        builder: (context, RecommendProvider recommendProvider, _) =>
            textWidget,
      );
    } else if (providerType == 'latest') {
      return Consumer<LatestProvider>(
        builder: (context, LatestProvider latestProvider, _) => textWidget,
      );
    } else {
      return Consumer<AttentionProvider>(
        builder: (context, AttentionProvider attentionProvider, _) =>
            textWidget,
      );
    }
  }

  // 底部弹出框
  Future<Widget> _show(BuildContext context, int itemId) {
    return showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return AnimatedPadding(
          padding: MediaQuery.of(context).viewInsets, //边距（必要）
          duration: const Duration(milliseconds: 100), //时常 （必要,
          child: ShowCommunityInput(
            itemId: itemId,
            rId: -1,
            providerType: _providerType,
          ),
        );
      },
    );
  }
}
